package com.litong.litongjiaoyu.interceptor;

import com.litong.litongjiaoyu.annotation.IgnoreAuth;
import com.litong.litongjiaoyu.entity.TeacherUserinfo;
import com.litong.litongjiaoyu.exception.ApiRRException;
import com.litong.litongjiaoyu.service.TeacherService;
import com.litong.litongjiaoyu.service.UserSessionService;
import com.litong.litongjiaoyu.utils.RedisUtil;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AuthorizationInterceptor
 * @Description 权限(Token)验证，作用环境，小程序调用后台接口检验是否授权
 * @Description 此拦截器作用方式是判断请求头里面的token是否过期或者是否有token数据既判断出是否需要拦截进行授权跳转
 * @Author jingz
 * @Date 2020/2/1 14:36
 * @Version 1.0
 **/
@Log4j2
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    /**
     * 此为存储用户token的表service层，用来控制用户token的过期与否
     */
    @Autowired
    private UserSessionService tokenService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 存储微信用户信息的表
     */
    @Autowired
    private TeacherService teacherService;


    public static final String LOGIN_USER_KEY = "LOGIN-USER-KEY";
    public static final String LOGIN_TOKEN_KEY = "X-Nideshop-Token";
    public static final String LOGIN_USER_TYPE = "LOGIN-USER-TYPE";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //支持跨域请求
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,LOGIN-USER-KEY,X-URL-PATH,LOGIN-USER-TYPE");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));


        //设置跨域--结束

        //这块涉及到一个自定义注解，忽略验证
        IgnoreAuth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);

            log.info(String.format("url:%s, annotation:%s", request.getRequestURL(), annotation));
        } else {
            return true;
        }

        //如果有@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return true;
        }

        //从header中获取token
        String openid = request.getHeader(LOGIN_USER_KEY);
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(openid)) {
            openid = request.getParameter(LOGIN_USER_KEY);
        }

        //token为空
        if (StringUtils.isBlank(openid)) {
            throw new ApiRRException("请先登录", 401);
        }

        //查询token信息
        boolean aaa = redisUtil.have(openid);
        if (!aaa) {
            throw new ApiRRException("token失效，请重新登录", 401);
        }

        //设置userId到request里，后续根据userId，获取用户信息

        String openidStr = (String) redisUtil.get("user-redis-session:" + openid);

        request.setAttribute(LOGIN_TOKEN_KEY, openidStr);

        String type = request.getHeader(LOGIN_USER_TYPE);

        if (!type.equals("student")) {
            //根据userId查询用户的信息，检测是否有手机号，没有手机号，重新跳转页面至获取手机号页面
            TeacherUserinfo teacher = teacherService.selectTeacherInfo(openid);
            if (teacher == null) {
                throw new ApiRRException("用户不存在", 401);
            } else {
                if (teacher.getPosition() == 1) {
                    throw new ApiRRException("用户没有访问权限", 403);
                }
            }
        } else {
            log.info("放行");
        }
        return true;
    }
}

